package com.walk.zworld.ui.activity.my

import android.animation.Animator
import android.animation.ValueAnimator
import android.os.Build
import android.view.animation.DecelerateInterpolator
import android.widget.ProgressBar
import androidx.annotation.RequiresApi
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.walk.zworld.R
import com.walk.zworld.mvvm.vm.MyRankActivityViewModel
import com.walk.zworld.webView.WebViewActivity
import com.base.lib.base.view.BaseMvvmListActivity
import com.base.lib.httpUtils.CoinInfoBean

class RankActivity : BaseMvvmListActivity<CoinInfoBean, MyRankActivityViewModel, RankActivity.RankAdapter>() {

    override fun onBindAdapter(): Class<RankAdapter> = RankAdapter::class.java

    override fun onBindViewModel(): Class<MyRankActivityViewModel> = MyRankActivityViewModel::class.java

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun initData() {
        setTop("积分排行榜")
        setRight(R.drawable.wenhao) {
            val url = "https://www.wanandroid.com/blog/show/2653"
            WebViewActivity.start(this, 2653, "", url)
        }
    }

    override fun initView() {  //
    }


    class RankAdapter : BaseQuickAdapter<CoinInfoBean, BaseViewHolder>(R.layout.rank_list_item),
        LoadMoreModule {

        private val mScale = 1000
        private var mMax = 0

        override fun convert(holder: BaseViewHolder, item: CoinInfoBean) {
            mMax = data[0].coinCount
            val pb = holder.getView<ProgressBar>(R.id.pb_rank_list)
            pb.max = mMax * mScale
            cancelProgressAnim(pb)
            if (!item.anim) {
                item.anim = true
                doProgressAnim(pb, item.coinCount)
            } else pb.progress = item.coinCount * mScale
            holder.setText(R.id.tv_rank_num, "${holder.layoutPosition + 1}")
            holder.setText(R.id.tv_rank_name, item.username)
            holder.setText(R.id.tv_rank_count, "${item.coinCount}")
        }

        private fun doProgressAnim(pb: ProgressBar, to: Int) {
            val animator = ValueAnimator.ofInt(0, to)
            animator.duration = 1000
            animator.interpolator = DecelerateInterpolator()
            animator.addUpdateListener { animation ->
                pb.progress = animation.animatedValue as Int * mScale
            }
            pb.tag = animator
            animator.start()
        }

        private fun cancelProgressAnim(pb: ProgressBar) {
            val obj = pb.tag
            if (obj is Animator) {
                obj.cancel()
            }
            pb.tag = null
        }
    }
}